<template>
  <div class="navbar">
    <div class="left-side">
      <a-space>
        <img alt="logo" src="@/assets/images/logo_32.png" />
        <a-typography-title
          :style="{ margin: 0, fontSize: '18px' }"
          :heading="5"
        >
          {{ title }}
        </a-typography-title>
        <icon-menu-fold
          v-if="!topMenu && appStore.device === 'mobile'"
          style="font-size: 22px; cursor: pointer"
          @click="toggleDrawerMenu"
        />
      </a-space>
    </div>
    <div class="center-side">
      <Menu v-if="topMenu" />
    </div>
    <ul class="right-side">
      <li>
        <a-tooltip :content="$t('settings.language')">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setDropDownVisible"
          >
            <template #icon>
              <icon-language />
            </template>
          </a-button>
        </a-tooltip>
        <a-dropdown trigger="click" @select="changeLocale as any">
          <div ref="triggerBtn" class="trigger-btn"></div>
          <template #content>
            <a-doption
              v-for="item in locales"
              :key="item.value"
              :value="item.value"
            >
              <template #icon>
                <icon-check v-show="item.value === currentLocale" />
              </template>
              {{ item.label }}
            </a-doption>
          </template>
        </a-dropdown>
      </li>
      <li>
        <a-tooltip
          :content="
            theme === 'light'
              ? $t('settings.navbar.theme.toDark')
              : $t('settings.navbar.theme.toLight')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="handleToggleTheme"
          >
            <template #icon>
              <icon-moon-fill v-if="theme === 'dark'" />
              <icon-sun-fill v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li>

      <li>
        <a-tooltip :content="$t('settings.navbar.alerts')">
          <a-badge :count="alertNum">
            <a-button
              class="nav-btn"
              type="outline"
              :shape="'circle'"
              @click="openAlerts"
            >
              <icon-notification />
            </a-button>
          </a-badge>
        </a-tooltip>
      </li>

      <li>
        <a-tooltip
          :content="
            isFullscreen
              ? $t('settings.navbar.screen.toExit')
              : $t('settings.navbar.screen.toFull')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="toggleFullScreen"
          >
            <template #icon>
              <icon-fullscreen-exit v-if="isFullscreen" />
              <icon-fullscreen v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-tooltip :content="$t('settings.title')">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setVisible"
          >
            <template #icon>
              <icon-settings />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-dropdown trigger="click">
          <a-avatar
            :size="32"
            :style="{
              marginRight: '8px',
              cursor: 'pointer',
              backgroundColor: 'blue',
            }"
          >
            {{ realName?.substring(0, 1) }}
          </a-avatar>
          <template #content>
            <a-doption>
              <a-space @click="changePasswdAction">
                <icon-lock />
                <span>修改密码</span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="handleLogout">
                <icon-export />
                <span>退出登录</span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>
    <modal-dialog
      v-model="changePwDialogVisible"
      title="修改密码"
      width="460"
      @confirm="handleChangePw"
    >
      <change-passwd ref="changePwFormRef"></change-passwd>
    </modal-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { useDark, useToggle, useFullscreen } from '@vueuse/core';
  import { computed, ref, inject } from 'vue';

  import { updatePwApi } from '@/api/system/authorization';
  import { getUnfinishedCountApi } from '@/api/system/excel-import';
  import Menu from '@/components/menu/index.vue';
  import ChangePasswd from '@/components/navbar/change-passwd.vue';
  import useLocale from '@/hooks/locale';
  import useUser from '@/hooks/user';
  import { LOCALE_OPTIONS } from '@/locale';
  import { useAppStore, useUserStore } from '@/store';

  const router = useRouter();
  const appStore = useAppStore();
  const userStore = useUserStore();
  const { logout } = useUser();
  const { changeLocale, currentLocale } = useLocale();
  const { isFullscreen, toggle: toggleFullScreen } = useFullscreen();

  const locales = [...LOCALE_OPTIONS];
  const title = ref(import.meta.env.VITE_APP_TITLE);
  const realName = ref(userStore.realName);

  const theme = computed(() => {
    return appStore.theme;
  });

  const topMenu = computed(() => appStore.topMenu && appStore.menu);

  const isDark = useDark({
    selector: 'body',
    attribute: 'arco-theme',
    valueDark: 'dark',
    valueLight: 'light',
    storageKey: 'arco-theme',
    onChanged(dark: boolean) {
      // overridden default behavior
      appStore.toggleTheme(dark);
    },
  });

  const toggleTheme = useToggle(isDark);

  const handleToggleTheme = () => {
    toggleTheme();
  };

  const setVisible = () => {
    appStore.updateSettings({ globalSettings: true });
  };

  const triggerBtn = ref();

  const handleLogout = () => {
    logout();
  };

  const setDropDownVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    triggerBtn.value.dispatchEvent(event);
  };

  const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;

  const changePwDialogVisible = ref(false);
  const changePwFormRef = ref<ComponentRef<typeof ChangePasswd>>();

  const changePasswdAction = () => {
    changePwDialogVisible.value = true;
  };

  const handleChangePw = async () => {
    const formData = await changePwFormRef.value?.submit();
    if (formData) {
      const res = await updatePwApi(formData['password']);
      if (res) {
        MessageInfo.success();
        changePwDialogVisible.value = false;
        logout('', false);
      }
    }
  };

  const noticeNum = ref(0);
  const importExcelNum = ref(0);

  const alertNum = computed(() => {
    return noticeNum.value + importExcelNum.value;
  });

  const openAlerts = () => {
    router.push({ name: 'Alerts' });
  };

  onMounted(() => {
    getUnfinishedCountApi().then((res) => {
      if (res) {
        importExcelNum.value = res;
      }
    });
  });
</script>
<style scoped lang="less">
  .navbar {
    display: flex;
    justify-content: space-between;
    height: 100%;
    background-color: var(--color-bg-2);
    border-bottom: 1px solid var(--color-border);
  }

  .left-side {
    display: flex;
    align-items: center;
    padding-left: 20px;
  }

  .center-side {
    flex: 1;
  }

  .right-side {
    display: flex;
    padding-right: 20px;
    list-style: none;

    :deep(.locale-select) {
      border-radius: 20px;
    }

    li {
      display: flex;
      align-items: center;
      padding: 0 10px;
    }

    a {
      color: var(--color-text-1);
      text-decoration: none;
    }

    .nav-btn {
      color: rgb(var(--gray-8));
      font-size: 16px;
      border-color: rgb(var(--gray-2));
    }

    .trigger-btn {
      position: absolute;
      bottom: 14px;
    }

    .trigger-btn {
      margin-left: 14px;
    }
  }
</style>
